package com.ljy.jymail.order.listener;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.ljy.jymail.order.config.AlipayTemplate;
import com.ljy.jymail.order.entity.OrderEntity;
import com.ljy.jymail.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RabbitListener(queues = "order.release.order.queue")
@Slf4j
@Service
/*关单消息监听类*/
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @RabbitHandler
    public void listener(OrderEntity entity, Channel channel, Message message
            , HttpServletRequest request
    ) throws IOException {
//        System.out.println("收到订单信息,关闭订单"+entity.getId());
        try{
            orderService.closeOrder(entity);
            //可以手动调用支付宝收单
//            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(alipayTemplate.getGatewayUrl(), alipayTemplate.getApp_id(), alipayTemplate.getMerchant_private_key(), "json", alipayTemplate.getCharset(), alipayTemplate.getAlipay_public_key(), alipayTemplate.getSign_type());

            //设置请求参数
            AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = new String(request.getParameter("WIDTCout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("WIDTCtrade_no").getBytes("ISO-8859-1"),"UTF-8");
            //请二选一设置

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," +"\"trade_no\":\""+ trade_no +"\"}");

            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
